package fw_jwt

import (
	"github.com/golang-jwt/jwt/v5"
	"time"
	"transport/framework/fw_config"
)

type CustomClaims struct {
	UserId   int64
	Username string
	Phone    string
	jwt.RegisteredClaims
}

func GenJwt(userId int64, username, phone string) (signToken string, err error, retClaims CustomClaims) {
	mySigningKey := []byte(fw_config.GetConfigHandler().GetString("jwt.signSecret"))
	// Create the claims
	claims := CustomClaims{
		userId,
		username,
		phone,
		jwt.RegisteredClaims{
			// A usual scenario is to set the expiration time relative to the current time
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(fw_config.GetConfigHandler().GetDuration("jwt.expireDuration") * time.Hour)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			//NotBefore: jwt.NewNumericDate(time.Now()),
			//Issuer:    "test",
			//Subject:   "somebody",
			//ID:        "1",
			//Audience:  []string{"somebody_else"},
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	signToken, err = token.SignedString(mySigningKey)
	return signToken, err, claims
}

func ParseJwt(signToken string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(signToken, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(fw_config.GetConfigHandler().GetString("jwt.signSecret")), nil
	})
	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		return claims, nil
	}
	return nil, err
}
